package com.blast.comicsisland.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * author : hg
 * email: 530157892@qq.com
 * 15/6/9.
 */

/**
 * 图片下载器
 */
public class ImageLoadTask extends AsyncTask<String, Void, Bitmap> {

    private ImageView imageView;
    private String url;

    /**
     * 加载图片给特定的ImageView
     *
     * @param imageView 在加入ImageView的时候，进行标识：setTag（）
     */
    public ImageLoadTask(ImageView imageView) {
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        Bitmap ret = null;

        if (params != null && params.length > 0) {
            url = params[0];
            ImageCache imageCache = ImageCache.getInstant();
            Bitmap bitmap = imageCache.get(url);
            if (bitmap != null) {
                ret = bitmap;
            } else {
                File targetFile = null;

                String sdcardState = Environment.getExternalStorageState();

                if (sdcardState.equals(Environment.MEDIA_MOUNTED)) {
                    File storageDirectory = Environment.getExternalStorageDirectory();

                    File imageCacheRoot = new File(storageDirectory, ".test/images");

                    boolean b = true;

                    if (!imageCacheRoot.exists()) {
                        b = imageCacheRoot.mkdir();
                    }

                    if (b) {
                        String fileName = CacheUtils.md5(url);
                        targetFile = new File(imageCacheRoot, fileName);
                    }

                }

                if (targetFile == null || !targetFile.exists()) {

                    try {
                        URL u = new URL(url);

                        HttpURLConnection conn = (HttpURLConnection) u.openConnection();

                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        conn.setDoInput(true);

                        conn.connect();

                        InputStream inputStream = conn.getInputStream();

                        byte[] data = CommentHttpUtil.readStream(inputStream);

                        inputStream.close();

                        conn.disconnect();

                        if (targetFile != null) {

                            boolean b = targetFile.createNewFile();

                            if (b) {
                                FileOutputStream fos = null;
                                try {
                                    fos = new FileOutputStream(targetFile);
                                    fos.write(data, 0, data.length);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    if (fos != null) {
                                        try {
                                            fos.close();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }

                        ret = BitmapFactory.decodeByteArray(data, 0, data.length);

                        if (ret != null) {
                            imageCache.put(url, ret);
                        }

                        data = null;

                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } else {
                    ret = BitmapFactory.decodeFile(targetFile.getAbsolutePath());
                    imageCache.put(url, ret);
                }
            }

        }
        return ret;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap != null) {
            if (imageView != null) {
                Object tag = imageView.getTag();
                if (tag != null && tag instanceof String){
                    String s = (String) tag;
                    if (s.equals(url)){
                        imageView.setImageBitmap(bitmap);
                    }
                }
            }

        }
    }
}
